package com.eduagent.xwqeduagent.tools;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.eduagent.xwqeduagent.exception.BusinessException;
import com.eduagent.xwqeduagent.exception.ErrorCode;
import com.eduagent.xwqeduagent.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class PictureCaptureTool {

    @Tool(description = "Batch capture and create pictures based on search text. Returns a list of picture URLs.")
    public List<String> capturePictures(
            @ToolParam(description = "Search text for pictures") String searchText,
            @ToolParam(description = "Number of pictures to capture, max 30") Integer count,
            @ToolParam(description = "Offset for pagination") Integer offset) {

        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");

        // 构造抓取 URL，包含偏移量参数
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1&first=%d", searchText, offset);
        log.info("开始抓取图片，关键词: {}, 偏移量: {}, 抓取数量: {}", searchText, offset, count);

        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }

        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }

        Elements imgElementList = div.select("img.mimg");
        List<String> pictureList = new ArrayList<>();
        int uploadedCount = 0; // 变量名修改，避免与参数名冲突

        for (Element imgElement : imgElementList) {
            if (uploadedCount >= count) { // 先判断是否已达到数量上限
                break;
            }

            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }

            // 处理图片 URL，移除 URL 中的 `?` 之后的参数，防止转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            pictureList.add(fileUrl);
            uploadedCount++;
        }
        return pictureList;
    }
}